package com.guli.acl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.acl.entity.Permission;
import com.guli.acl.entity.RolePermission;
import com.guli.acl.entity.User;
import com.guli.acl.helper.MemuHelper;
import com.guli.acl.helper.PermissionHelper;
import com.guli.acl.mapper.PermissionMapper;
import com.guli.acl.service.PermissionService;
import com.guli.acl.service.RolePermissionService;
import com.guli.acl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author ZhaoZhenyu
 * @since 2022-10-06
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private UserService userService;

    /**
     * 递归查找菜单
     * @return
     */
    @Override
    public List<Permission> queryAllMenu() {
        List<Permission> permissionList = baseMapper.selectList(new QueryWrapper<Permission>().orderByDesc("id"));
        // 递归创建菜单 父菜单里面有子菜单
        return PermissionHelper.build(permissionList);
    }

    /**
     * 递归删除菜单
     * @param id
     */
    @Override
    public void removeChildById(String id) {
        ArrayList<String> idList = new ArrayList<>();
        // 父节点先放进去
        idList.add(id);
        // 递归把子节点放进idList
        this.addChildById(id,idList);
        baseMapper.deleteBatchIds(idList);
    }

    /**
     * 分配权限
     * @param roleId
     * @param permissionIds
     */
    @Override
    public void saveRolePermissionRelationShip(String roleId, String[] permissionIds) {
        rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        ArrayList<RolePermission> rolePermissionList = new ArrayList<>();
        for (String permissionId : permissionIds) {
            if (StringUtils.isEmpty(permissionId))continue;
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(permissionId);
            rolePermission.setRoleId(roleId);
            rolePermissionList.add(rolePermission);
        }
        rolePermissionService.saveBatch(rolePermissionList);
    }

    /**
     * 根据id获取权限列表
     * @param id
     * @return
     */
    @Override
    public List<String> selectPermissionValueByUserId(String id) {
        List<String> selectPermissionValueList = null;
        if(this.isSysAdmin(id)) {
            //如果是系统管理员，获取所有权限
            selectPermissionValueList = baseMapper.selectAllPermissionValue();
        } else {
            selectPermissionValueList = baseMapper.selectPermissionValueByUserId(id);
        }
        return selectPermissionValueList;
    }

    @Override
    public List<JSONObject> selectPermissionByUserId(String userId) {
        List<Permission> selectPermissionList = null;
        if(this.isSysAdmin(userId)) {
            //如果是超级管理员，获取所有菜单
            selectPermissionList = baseMapper.selectList(null);
        } else {
            selectPermissionList = baseMapper.selectPermissionByUserId(userId);
        }

        List<Permission> permissionList = PermissionHelper.build(selectPermissionList);
        List<JSONObject> result = MemuHelper.build(permissionList);
        return result;
    }

    @Override
    public List<Permission> selectAllMenu(String roleId) {
        List<Permission> allPermissionList = baseMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));

        //根据角色id获取角色权限
        List<RolePermission> rolePermissionList = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("role_id",roleId));
        for (int i = 0; i < allPermissionList.size(); i++) {
            Permission permission = allPermissionList.get(i);
            for (int m = 0; m < rolePermissionList.size(); m++) {
                RolePermission rolePermission = rolePermissionList.get(m);
                if(rolePermission.getPermissionId().equals(permission.getId())) {
                    permission.setSelect(true);
                }
            }
        }
        List<Permission> permissionList = PermissionHelper.build(allPermissionList);
        return permissionList;
    }

    private boolean isSysAdmin(String userId) {
        User user = userService.getById(userId);
        if(null != user && "admin".equals(user.getUsername())) {
            return true;
        }
        return false;
    }

    /**
     *
     * @param id
     * @param idList
     */
    private void addChildById(String id, ArrayList<String> idList) {
        // 找pid与父节点id相等的元素
        List<Permission> childList = baseMapper.selectList(new QueryWrapper<Permission>().eq("pid", id).select("id"));
        childList.stream().forEach(item -> {
            idList.add(item.getId());
            this.addChildById(item.getId(),idList);
        });
    }


}
